/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fujitsu.nanjing.tieba.base.BaseController;
import com.fujitsu.nanjing.tieba.common.Dialog;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.exception.Resource404Exception;
import com.fujitsu.nanjing.tieba.ibator.CoreBookmark;
import com.fujitsu.nanjing.tieba.ibator.CoreCreditsLog;
import com.fujitsu.nanjing.tieba.ibator.CoreFriend;
import com.fujitsu.nanjing.tieba.ibator.CoreGroup;
import com.fujitsu.nanjing.tieba.ibator.CoreReply;
import com.fujitsu.nanjing.tieba.ibator.CoreShortMsg;
import com.fujitsu.nanjing.tieba.ibator.CoreTopic;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.BookmarkService;
import com.fujitsu.nanjing.tieba.service.CreditsLogService;
import com.fujitsu.nanjing.tieba.service.FriendService;
import com.fujitsu.nanjing.tieba.service.GroupService;
import com.fujitsu.nanjing.tieba.service.ReplyService;
import com.fujitsu.nanjing.tieba.service.ShortMessageService;
import com.fujitsu.nanjing.tieba.service.TopicService;
import com.fujitsu.nanjing.tieba.service.UserService;

/**
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/forum/members")
public class MembersController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private TopicService topicService;
	@Resource
	private ReplyService replyService;
	@Resource
	private GroupService groupService;
	@Resource
	private ShortMessageService shortMessageService;
	@Resource
	private BookmarkService bookMarkService;
	@Resource
	private FriendService friendService;
	@Resource
	private CreditsLogService creditsLogService;

	@RequestMapping(value = {"/{memberid}"}, method = RequestMethod.GET)
	public String showMember(Model model, @PathVariable String memberid) {
		return redirect("/forum/members/" + memberid + "/topics");
	}
	@RequestMapping(value = {"/{memberid}/topics"}, method = RequestMethod.GET)
	public String showTopics(Model model, @PathVariable String memberid)
			throws Resource404Exception {
		return redirect("/forum/members/" + memberid + "/topics/pages/1");
	}
	@RequestMapping(value = {"/{memberid}/topics/pages/{pageIndex}"}, method = RequestMethod.GET)
	public String showTopics(Model model, @PathVariable String memberid,
			@PathVariable String pageIndex) throws Resource404Exception {
		CoreUser user = userService.findById(memberid);
		if (user == null) {
			throw new Resource404Exception("此用户不存在，或已被删除！");
		}
		model.addAttribute("user", user);
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		List<CoreTopic> topics = topicService.findTopicByUserId(memberid,
				Integer.parseInt(pageIndex));
		model.addAttribute("pageCount",
				topicService.findPageCountByUserId(memberid));
		model.addAttribute("topics", topics);
		model.addAttribute("type", "topic");
		return "/userSpace/userSpace";
	}
	@RequestMapping(value = {"/{memberid}/replies"}, method = RequestMethod.GET)
	public String showReplies(Model model, @PathVariable String memberid)
			throws Resource404Exception {
		return redirect("/forum/members/" + memberid + "/replies/pages/1");
	}
	@RequestMapping(value = {"/{memberid}/replies/pages/{pageIndex}"}, method = RequestMethod.GET)
	public String showReplies(Model model, @PathVariable String memberid,
			@PathVariable String pageIndex) throws Resource404Exception {
		CoreUser user = userService.findById(memberid);
		if (user == null) {
			throw new Resource404Exception("此用户不存在，或已被删除！");
		}
		model.addAttribute("user", user);
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		List<CoreReply> replies = replyService.findRepliesByUserId(memberid,
				Integer.parseInt(pageIndex));
		model.addAttribute("pageCount",
				replyService.findPageCountByUserId(memberid));
		model.addAttribute("replies", replies);
		model.addAttribute("type", "reply");
		return "/userSpace/userSpace";
	}
	@RequestMapping(value = "/myProfile", method = RequestMethod.GET)
	public String myProfile(Model model) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "myProfile");
		model.addAttribute("type", "myProfile");
		model.addAttribute("gender", userService.initGender());
		return "userSpace/profile/profile";
	}

	@RequestMapping(value = "/myProfile/changePassword", method = RequestMethod.GET)
	public String changePassword(Model model) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "myProfile");
		model.addAttribute("type", "password");
		return "userSpace/profile/profile";
	}
	@RequestMapping(value = "/myProfile/special", method = RequestMethod.GET)
	public String special(Model model) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "myProfile");
		model.addAttribute("type", "special");
		model.addAttribute("dialog", Dialog.instance().setContent(getContent()));
		return "userSpace/profile/profile";
	}
	@RequestMapping(value = "/myRights", method = RequestMethod.GET)
	public String myRights(Model model) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		CoreGroup group = groupService.findById(user.getGroupid());
		// 此处不得使用group，groupTool使用group为变量
		model.addAttribute("coreGroup", group);
		model.addAttribute("mySpaceType", "myRights");
		model.addAttribute("type", "myRights");
		return "myRights/myRights";
	}
	@RequestMapping(value = "/myRights/gid/{groupId}", method = RequestMethod.GET)
	public String groupRights(@PathVariable String groupId, Model model)
			throws Resource404Exception {
		CoreGroup group = groupService.findById(groupId);
		if (group == null) {
			throw new Resource404Exception("没有该组别！");
		}
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("coreGroup", group);
		if (group.getGrouptype().equalsIgnoreCase(CommonParamter.MEMBER_GROUP)) {
			model.addAttribute("type", "member");
		} else {
			model.addAttribute("type", "system");
		}
		model.addAttribute("mySpaceType", "myRights");
		return "myRights/myRights";
	}
	@RequestMapping(value = "/myProfile/changePassword", method = RequestMethod.PUT)
	public String changePassword(Model model, String oldpwd, String pwd1,
			String pwd2, HttpSession session) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		if (user.getPwd().equals(encrypt(oldpwd))) {
			if (pwd1.equals(pwd2)) {
				user.setPwd(encrypt(pwd1));
				userService.update(user);
				model.addAttribute("message",
						"您已经成功的修改了密码！请重新<a href='/login'>登录</a>");
				setLogOutStatus(session);
			} else {
				model.addAttribute("message", "两次输入密码不符！");
			}

		}
		model.addAttribute("message", "您输入的密码不正确！");
		return "/myforum/perform";

	}
	@RequestMapping(value = "/myProfile/changeProfile", method = RequestMethod.PUT)
	public String changeProfile(Model model, CoreUser user, HttpSession session) {
		if (user.getIsmailpub() == null) {
			user.setIsmailpub(CommonParamter.NO);
		}
		if (user.getNickname() == null || user.getNickname().trim().equals("")) {
			user.setNickname(user.getUserid());
		}
		userService.update(user);
		session.setAttribute(CURRENTUSER, user.getNickname());
		return redirect("/forum/members/myProfile");
	}

	@RequestMapping(value = "/myProfile/changeSpecial", method = RequestMethod.PUT)
	public String changeSpecial(Model model, CoreUser user) {
		userService.update(user);
		// TODO;还有上传自定义图片没有实现
		return redirect("/forum/members/myProfile/special");
	}
	@RequestMapping(value = "/smsList", method = RequestMethod.GET)
	public String sms(Model model) {
		return redirect("/forum/members/smsList/inbox/pages/1");
	}
	@RequestMapping(value = "/smsList/inbox/pages/{pageIndex}", method = RequestMethod.GET)
	public String smsWithPage(Model model, @PathVariable String pageIndex) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "smsList");
		List<CoreShortMsg> msgs = shortMessageService
				.findInShortMessagesByUserId(user.getUserid(),
						Integer.parseInt(pageIndex));
		model.addAttribute("msgs", msgs);
		model.addAttribute("pageCount",
				shortMessageService.findPageCountByUserId(user.getUserid()));
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("type", "inbox");
		model.addAttribute("unread",
				shortMessageService.countUnReadByUserId(user.getUserid()));
		return "sms/sms";
	}
	@RequestMapping(value = "/smsList/outbox", method = RequestMethod.GET)
	public String outBox() {
		return redirect("/forum/members/smsList/outbox/pages/1");
	}
	@RequestMapping(value = "/smsList/outbox/pages/{pageIndex}", method = RequestMethod.GET)
	public String outBoxWithPage(Model model, @PathVariable String pageIndex) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "smsList");
		List<CoreShortMsg> msgs = shortMessageService
				.findOutShortMessagesByFromUserId(user.getUserid(),
						Integer.parseInt(pageIndex));
		model.addAttribute("msgs", msgs);
		model.addAttribute("pageCount",
				shortMessageService.findPageCountByFromUserId(user.getUserid()));
		model.addAttribute("pageIndex", pageIndex);
		model.addAttribute("type", "outbox");
		model.addAttribute("unread",
				shortMessageService.countUnReadByUserId(user.getUserid()));
		return "sms/sms";
	}
	@RequestMapping(value = "/smsList/smscompose", method = RequestMethod.GET)
	public String smscompose(Model model, String subject, String userId,
			String msgId) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "smsList");
		model.addAttribute("type", "additem");
		model.addAttribute("unread",
				shortMessageService.countUnReadByUserId(user.getUserid()));
		model.addAttribute("subject", subject);
		model.addAttribute("user", userId);
		if (msgId != null) {
			CoreShortMsg msg = shortMessageService.findById(msgId);
			if (msg != null) {
				model.addAttribute("message", msg.getMessage());
			}
		}
		return "sms/sms";
	}
	@RequestMapping(value = "/smsList/smscompose", method = RequestMethod.POST)
	public String compose(Model model, String users, String subject,
			String message, String sendmail) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "smsList");
		model.addAttribute("type", "additem");
		model.addAttribute("unread",
				shortMessageService.countUnReadByUserId(user.getUserid()));
		shortMessageService.sendMsg(users, filterWord(subject),
				filterWord(message), sendmail);
		return redirect("/forum/members/smsList/outbox");

	}
	@RequestMapping(value = "/smsList/outbox", method = RequestMethod.DELETE)
	public String deleteOutMsgs(Model model, String msgID) {
		shortMessageService.deleteOutShortMsgs(msgID);
		return redirect("/forum/members/smsList/outbox/pages/1");

	}
	@RequestMapping(value = "/smsList/inbox", method = RequestMethod.DELETE)
	public String deleteInMsgs(Model model, String msgID) {
		shortMessageService.deleteInShortMsgs(msgID);
		return redirect("/forum/members/smsList/inbox/pages/1");

	}
	@RequestMapping(value = "/smsList/box", method = RequestMethod.POST)
	@ResponseBody
	public boolean readShortMsg(Model model, String msgId,
			HttpServletRequest request) {
		if (shortMessageService.readShortMsg(msgId)) {
			return true;
		}
		return false;
	}
	@RequestMapping(value = "/addFavor", method = RequestMethod.GET)
	public String addFavor(Model model, String url, String boardName,
			String title) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "myFavors");
		model.addAttribute("type", "additem");
		model.addAttribute("boardName", boardName);
		model.addAttribute("subject", title);
		model.addAttribute("url", url);
		return "favors/favors";
	}
	@RequestMapping(value = "/addFavor", method = RequestMethod.POST)
	public String addFavor(Model model, CoreBookmark bookMark) {
		UserDetails user = getUserDetails();
		bookMark.setUserid(user.getUsername());
		bookMarkService.insert(bookMark);
		return redirect("/forum/members/myFavors");
	}
	@RequestMapping(value = "/myFavors", method = RequestMethod.GET)
	public String showFavors(Model model) {
		return redirect("/forum/members/myFavors/pages/1");
	}
	@RequestMapping(value = "/myFavors/pages/{pageIndex}", method = RequestMethod.GET)
	public String showFavorsWithPage(Model model, @PathVariable String pageIndex) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		List<CoreBookmark> favors = bookMarkService.findFavorsByUserId(
				userDetails.getUsername(), Integer.parseInt(pageIndex));
		model.addAttribute("favors", favors);
		model.addAttribute("mySpaceType", "myFavors");
		model.addAttribute("type", "myFavors");
		model.addAttribute("pageCount", bookMarkService
				.findPageCountByUserId(userDetails.getUsername()));
		return "favors/favors";
	}
	@RequestMapping(value = "/myFavors", method = RequestMethod.DELETE)
	public String deleteFavors(String markID) {
		bookMarkService.deleteFavors(markID);
		return redirect("myFavors/pages/1");
	}
	@RequestMapping(value = "/myFriends", method = RequestMethod.GET)
	public String showFriends() {
		return redirect("/forum/members/myFriends/pages/1");
	}
	@RequestMapping(value = "/myFriends/pages/{pageIndex}", method = RequestMethod.GET)
	public String showFriends(Model model, @PathVariable String pageIndex) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		List<CoreFriend> friends = friendService.findByUseridWithPageNum(
				userDetails.getUsername(), Integer.parseInt(pageIndex));
		model.addAttribute("friends", friends);
		model.addAttribute("mySpaceType", "myFriends");
		model.addAttribute("type", "myFriends");
		model.addAttribute("pageCount",
				friendService.findPageCountByUserId(userDetails.getUsername()));
		return "friends/friends";
	}
	@RequestMapping(value = "/myFriends", method = RequestMethod.DELETE)
	public String deleteFriends(Model model, String friendID) {
		friendService.deleteFriends(friendID);
		return redirect("/forum/members/myFriends/pages/1");

	}
	@RequestMapping(value = "/addFriend", method = RequestMethod.GET)
	public String addFriends(Model model, String friendId) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		model.addAttribute("mySpaceType", "myFriends");
		model.addAttribute("type", "additem");
		model.addAttribute("friendId", friendId);
		return "friends/friends";
	}
	@RequestMapping(value = "/addFriend", method = RequestMethod.POST)
	public String addFriends(String friendID, String remark) {
		friendService.insert(friendID, remark);
		return redirect("/forum/members/myFriends/pages/1");
	}
	@RequestMapping(value = "/checkfriendId", method = RequestMethod.POST)
	@ResponseBody
	public boolean checkfriendId(String friendId) {
		CoreUser user = userService.findById(friendId);
		String username = getUserDetails().getUsername();
		if (username.equals(friendId)) {
			/* return "不可以加自己为好友"; */
			return false;
		}
		if (user != null) {
			if (friendService.findByKey(username, friendId) != null) {
				/* return "该用户已经是您的好友"; */
				return true;
			} else {
				/* return "true"; */
				return true;
			}
		} else {
			/* return "该用户不存在"; */
			return false;
		}
	}
	@RequestMapping(value = "/checkEmail", method = RequestMethod.POST)
	@ResponseBody
	public boolean checkEmail(String email) {
		String userId = getUserDetails().getUsername();
		CoreUser user = userService.findById(userId);
		if (user.getEmail().equals(email)) {
			/* return "可以不更改email"; */
			return true;
		}
		int count = userService.findByEmail(email);
		if (count != 0) {
			return false;
		} else {
			return true;
		}
	}
	@RequestMapping(value = {"/incCredits", "/myCredits"}, method = RequestMethod.GET)
	public String incCredits() {
		return redirect("/forum/members/incCredits/pages/1");
	}
	@RequestMapping(value = "/decCredits", method = RequestMethod.GET)
	public String decCredits() {
		return redirect("/forum/members/decCredits/pages/1");
	}
	@RequestMapping(value = "/incCredits/pages/{pageIndex}", method = RequestMethod.GET)
	public String incCreditsWithPage(Model model, @PathVariable String pageIndex) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		List<CoreCreditsLog> credits = creditsLogService
				.findByUseridWithPageNum(userDetails.getUsername(),
						Integer.parseInt(pageIndex));
		model.addAttribute("credits", credits);
		model.addAttribute("mySpaceType", "myCredits");
		model.addAttribute("type", "incCredits");
		model.addAttribute("pageCount", creditsLogService
				.findPageCountByUserId(userDetails.getUsername()));
		return "credits/credits";
	}
	@RequestMapping(value = "/decCredits/pages/{pageIndex}", method = RequestMethod.GET)
	public String decCreditsWithPage(Model model, @PathVariable String pageIndex) {
		UserDetails userDetails = getUserDetails();
		CoreUser user = userService.findById(userDetails.getUsername());
		model.addAttribute("user", user);
		pageIndex = (pageIndex == null ? "0" : pageIndex);
		model.addAttribute("pageIndex", pageIndex);
		List<CoreCreditsLog> credits = creditsLogService.findByFromUserid(
				userDetails.getUsername(), Integer.parseInt(pageIndex));
		model.addAttribute("credits", credits);
		model.addAttribute("mySpaceType", "myCredits");
		model.addAttribute("type", "decCredits");
		model.addAttribute("pageCount", creditsLogService
				.findPageCountByFromUser(userDetails.getUsername()));
		return "credits/credits";
	}
	@RequestMapping(value = "/myTopics")
	public String myTopics() {
		String memberid = getUserDetails().getUsername();
		return redirect("/forum/members/" + memberid + "/topics/pages/1");
	}
	@RequestMapping(value = "/upload")
	@ResponseBody
	public String uploadPicture(Model model,
			MultipartHttpServletRequest mhsRequest) {
		Map<String, MultipartFile> files = mhsRequest.getFileMap();
		initWebRoot();
		List<String> links = savePhoto(files);
		if (links.size() > 0) {
			return links.get(0);
		}
		return "/resource/logo.gif";

	}
	private List<String> savePhoto(Map<String, MultipartFile> files) {
		List<String> links = new ArrayList<String>();
		for (Entry<String, MultipartFile> entry : files.entrySet()) {
			MultipartFile file = entry.getValue();
			if (file.getContentType().startsWith("image")) {
				logger.info("上传图片：" + file.getOriginalFilename());
			} else {
				logger.info("上传文件：" + file.getOriginalFilename());
			}
			// 产生随机的名字
			String tempName = String.valueOf(System.nanoTime())
					+ file.getOriginalFilename().substring(
							file.getOriginalFilename().lastIndexOf("."));
			// 将文件写入upload目录下
			File dest = new File(CommonParamter.webRoot
					+ CommonParamter.avaterPath + File.separatorChar + tempName);
			links.add(tempName);
			try {
				file.transferTo(dest);
			} catch (IllegalStateException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		}
		return links;
	}
}
